package com.fingard.dsp.bank.directbank.cmb01;

import com.fingard.dsp.bank.directbank.bankInterface.IBalanceCheck;
import com.fingard.dsp.bank.reqrespobj.balancecheck.ReqBalCheckQry;
import com.fingard.dsp.bank.reqrespobj.balancecheck.RetAtsBalCheckQry;
import com.fingard.dsp.bank.reqrespobj.balancecheck.detail.RetAtsBalCheckDetail;
import com.fingard.text.StringHelper;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author Parker on 2019-09-23.
 * @version 1.0
 */
public class CMB01BalanceCheck extends CMB01Base implements IBalanceCheck {
    @Override
    public RetAtsBalCheckQry d_7508_BalCheck(ReqBalCheckQry p_req7508) throws Exception {
        //余额对账查询返回ATS的对象
        RetAtsBalCheckQry retAts = new RetAtsBalCheckQry(p_req7508.reqHeader, p_req7508.actNum);
        retAts.writeStart();//写返回ATS的统一头部信息
        try {
            CMB01Header tmpBnkHeader = new CMB01Header();
            tmpBnkHeader.FUNNAM = "NTNSTQRY1";

            String CNTFLG = "";
            int invokeCount = 0;//调用次数
            do {
            	invokeCount++;
            	if(invokeCount>10){
            		this.WriteBankLogAndLimit("CMB01BalanceCheck调用次数："+invokeCount);
            	}
                XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
                //写入通用的头部节点
                writeCommonHeader(xmlWriter, tmpBnkHeader);

                Date dateFrom = p_req7508.getYearMonth();
                xmlWriter.writeStartElement("NTNSTQRYX");
                xmlWriter.writeElementString("EACNBR", p_req7508.actNum);//账号
                xmlWriter.writeElementString("BUSMOD", "");//业务模式
                xmlWriter.writeElementString("YERMTH", new SimpleDateFormat("yyyyMM").format(dateFrom));//对账月份
                xmlWriter.writeElementString("ENDMTH", new SimpleDateFormat("yyyyMM").format(dateFrom));//结束对账月份
                xmlWriter.writeElementString("CNTFLG", "Y");//是否显示完成标志 取值待确定
                xmlWriter.writeEndElement();
                xmlWriter.writeEndDocument();
                String[] tmpRetBkStr = sendToBank(xmlWriter.toXmlString());
                //String[] tmpRetBkStr = new String[]{"","<?xml version=\"1.0\" encoding=\"GBK\"?><CMBSDKPGK><INFO><DATTYP>2</DATTYP><ERRMSG></ERRMSG><FUNNAM>NTNSTQRY1</FUNNAM><LGNNAM>学科园科兴学538</LGNNAM><RETCOD>0</RETCOD></INFO><NTNSTQRYX><CNTFLG>Y</CNTFLG><EACNBR>755915712410604</EACNBR><ECTFLG>1</ECTFLG><ENDMTH>201812</ENDMTH><YERMTH>201812</YERMTH></NTNSTQRYX></CMBSDKPGK>"};
                if (tmpRetBkStr[0].length() == 0) {
                    StringBuilder tmpSbMsg = new StringBuilder();
                    XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpRetBkStr[1], tmpSbMsg);
                    if (tmpBkReader != null) {
                        String returnCode = tmpBkReader.getFirstText("/CMBSDKPGK/INFO/RETCOD");
                        String returnInfo = tmpBkReader.getFirstText("/CMBSDKPGK/INFO/ERRMSG");
                        if ("0".equals(returnCode)) {
                            CNTFLG = tmpBkReader.getFirstText("/CMBSDKPGK/NTNSTQRYX/CNTFLG");
                            int count = 0;
                            while (tmpBkReader.read("/CMBSDKPGK/NTNSTQRYZ")) {
                                count++;
                                RetAtsBalCheckDetail tmpRetDetail = new RetAtsBalCheckDetail();
                                tmpRetDetail.actNum = tmpBkReader.readedXElement.getSingleText("EACNBR");
                                tmpRetDetail.statementNumber = tmpBkReader.readedXElement.getSingleText("BCHNBR"); //对账单编号,取批次号?
                                tmpRetDetail.yearMonth = tmpBkReader.readedXElement.getSingleText("YERMTH");
                                tmpRetDetail.actBal = tmpBkReader.readedXElement.getSingleText("ACTBAL");
                              //AcctType存款种类（1往来户,2贷款户,3定期户,4保证金户，5内部户，6个人贷款综合账户，9其他，34定期保证金户）
                                String tmpTDSTAG = tmpBkReader.readedXElement.getSingleText("TDSTAG");
                                if ("1".equals(tmpTDSTAG) || "Y".equalsIgnoreCase(tmpTDSTAG))
                                {
                                	tmpRetDetail.acctType = "34";
                                }
                                tmpRetDetail.actCur = convertCurToATS(tmpBkReader.readedXElement.getSingleTextNotNull("CCYNBR"));
                                if(StringHelper.isNullOrEmpty(tmpRetDetail.actCur)){
                                	tmpRetDetail.actCur = p_req7508.actCur;
                                }
                                tmpRetDetail.actSeq = tmpBkReader.readedXElement.getSingleTextNotNull("ACTSEQ");
                                tmpRetDetail.barCode = tmpBkReader.readedXElement.getSingleTextNotNull("BARCOD");
                                tmpRetDetail.barSeq = tmpBkReader.readedXElement.getSingleTextNotNull("BARSEQ");
                                tmpRetDetail.accNbr = tmpBkReader.readedXElement.getSingleTextNotNull("ACCNBR");
                                tmpRetDetail.iacNbr = tmpBkReader.readedXElement.getSingleTextNotNull("IACNBR");
                                tmpRetDetail.actCode = tmpBkReader.readedXElement.getSingleTextNotNull("ACTCOD");
                                tmpRetDetail.ccyType = tmpBkReader.readedXElement.getSingleTextNotNull("CCYTYP");
                                tmpRetDetail.lgrType = tmpBkReader.readedXElement.getSingleTextNotNull("LGRTYP");
                                tmpRetDetail.prcBrn = tmpBkReader.readedXElement.getSingleTextNotNull("PRCBRN");
                                tmpRetDetail.actBrn = tmpBkReader.readedXElement.getSingleTextNotNull("ACTBRN");
                                tmpRetDetail.lgrBrn = tmpBkReader.readedXElement.getSingleTextNotNull("LGRBRN");
                                tmpRetDetail.cltNbr = tmpBkReader.readedXElement.getSingleTextNotNull("CLTNBR");
                                tmpRetDetail.stmType = tmpBkReader.readedXElement.getSingleTextNotNull("STMTYP");
                                String balDate = tmpBkReader.readedXElement.getSingleTextNotNull("BALDAT");
                                if (balDate.length() == 8) {
                                    tmpRetDetail.balDate = balDate.substring(0, 4) + "-" + balDate.substring(4, 6) + "-" + balDate.substring(6, 8);
                                } else {
                                    tmpRetDetail.balDate = balDate;
                                }
                                tmpRetDetail.fixDate = tmpRetDetail.balDate;
                                tmpRetDetail.errTxt = tmpBkReader.readedXElement.getSingleText("ERRTXT");
                                tmpRetDetail.telNbr = tmpBkReader.readedXElement.getSingleText("TELNBR");
                                tmpRetDetail.checkSum  = tmpBkReader.readedXElement.getSingleText("SPLC20");
                                
                                tmpRetDetail.dateFrom = new SimpleDateFormat("yyyyMM").format(dateFrom) + "01";
                                tmpRetDetail.dateTo = dateConvert(dateFrom);
                                tmpRetDetail.respCode = "0";
                                tmpRetDetail.respInfo = returnInfo;
                                
                                //客户处理状态CustState
                                //招行1待经办，2待复核，3复核通过
                                //DSP 1待经办，4待复核，2复核通过
                                String tmpECTFLG = tmpBkReader.readedXElement.getSingleText("ECTFLG");
                                if ("1".equals(tmpECTFLG)){
                                	tmpRetDetail.custState = "1";
                                }else if ("2".equals(tmpECTFLG)){
                                	tmpRetDetail.custState = "4";
                                }else if ("3".equals(tmpECTFLG)){
                                	tmpRetDetail.custState = "2";
                                }
                                
                              //处理状态DealState
                                //招行 1已生成数据，3对账中，5对账完成
                                //DSP  1已生成数据，4对账中，2对账完成
                                String tmpSTSCOD = tmpBkReader.readedXElement.getSingleText("STSCOD");
                                if ("1".equals(tmpSTSCOD)){
                                	tmpRetDetail.dealState = "1";
                                }else if ("3".equals(tmpSTSCOD)){
                                	tmpRetDetail.dealState = "4";
                                }else if ("5".equals(tmpSTSCOD)){
                                	tmpRetDetail.dealState = "2";
                                }

                                if("1".equals(tmpSTSCOD) || "5".equals(tmpSTSCOD)){
                                    //余额核对状态：
                                    //招行Y余额相符，N余额不符，S调节相符，F调节不符
                                    //DSP Y余额相符，N余额不符，S调节相符，F调节不符，A未对账
                                    //    2平（余额相符），3不平（余额不符），1未对账，7调节相符
                                    String balFlag = tmpBkReader.readedXElement.getSingleText("BALFLG");
                                    if ("Y".equalsIgnoreCase(balFlag)) {
                                    	tmpRetDetail.dzFlag = "2";
                                    }else if("S".equalsIgnoreCase(balFlag)){
                                    	tmpRetDetail.dzFlag = "7";
                                    }else if ("N".equalsIgnoreCase(balFlag) || "F".equalsIgnoreCase(balFlag)) {
                                    	tmpRetDetail.dzFlag = "3";
                                    }else if ("A".equalsIgnoreCase(balFlag)){
                                    	tmpRetDetail.dzFlag = "1";
                                    }else{
                                    	tmpRetDetail.dzFlag = "1";
                                    }
                                }else{
                                	tmpRetDetail.dzFlag = "1";
                                }
                                
                                //借贷标志，1借，2贷
                                //招行       D借，C贷
                                String actDIR = tmpBkReader.readedXElement.getSingleText("ACTDIR");
                                if ("D".equalsIgnoreCase(actDIR)){
                                	tmpRetDetail.cdFlag = "1";
                                }else if ("C".equalsIgnoreCase(actDIR)){
                                	tmpRetDetail.cdFlag = "2";
                                }
                                retAts.writeRetDetail(tmpRetDetail);
                            }
                            if(count == 0){
                                retAts = new RetAtsBalCheckQry(p_req7508.reqHeader, p_req7508.actNum);
                                retAts.writeStart();//写返回ATS的统一头部信息
                                retAts.writeRespCode("-1");
                                retAts.writeRespInfo("银行未返回余额对账数据");
                            }
                        } else {
                            CNTFLG = "";
                            retAts = new RetAtsBalCheckQry(p_req7508.reqHeader, p_req7508.actNum);
                            retAts.writeStart();//写返回ATS的统一头部信息
                            retAts.writeRespCode("-1");
                            retAts.writeRespInfo(returnInfo);
                        }
                    } else {
                        CNTFLG = "";
                        retAts = new RetAtsBalCheckQry(p_req7508.reqHeader, p_req7508.actNum);
                        retAts.writeStart();//写返回ATS的统一头部信息
                        retAts.writeRespCode("-1");
                        retAts.writeRespInfo(tmpSbMsg.toString());
                    }
                } else {
                    CNTFLG = "";
                    retAts = new RetAtsBalCheckQry(p_req7508.reqHeader, p_req7508.actNum);
                    retAts.writeStart();//写返回ATS的统一头部信息
                    retAts.writeRespCode("-1");
                    retAts.writeRespInfo(tmpRetBkStr[1]);
                }
            } while ("N".equalsIgnoreCase(CNTFLG));
        } catch (Exception e) {
            retAts = new RetAtsBalCheckQry(p_req7508.reqHeader, p_req7508.actNum);
            retAts.writeStart();//写返回ATS的统一头部信息
            retAts.writeRespCode("-1");
            retAts.writeRespInfo(e.getMessage());
            this.WriteBankLogLn(e);
        }
        retAts.writeEnd();
        return retAts;
    }
}
